import requests
from pyquery import PyQuery as pq
import json
import pandas as pd
import math
import time
import re


'''
 <th>日期</th>&#13;
 <th>开盘价</th>&#13;
 <th>最高价</th>&#13;
 <th>最低价</th>&#13;
 <th>收盘价</th>&#13;
 <th>涨跌额</th>&#13;
 <th>涨跌幅(%)</th>&#13;
 <th>成交量(手)</th>&#13;
 <th>成交金额(万元)</th>&#13;
 <th>振幅(%)</th>&#13;
 <th>换手率(%)</th>&#13;

'''


def get_one_ticker_day_info(url, date):
    date_format = date[0:4] + '-' + date[4:6] + '-' + date[6:8]
    result = requests.get(url)
    doc = pq(result.text)
    # print(doc)
    ul = doc('.table_bg001')
    divs = ul('tr').items()
    #divs = doc('tbody').items()
    for div in divs:
        print(div)
        print(div('td').text())
        curr_list = div('td').text().split(' ')

        if len(curr_list) < 2:
            continue
        if curr_list[0] == date_format:
            return curr_list[1], curr_list[2], curr_list[4]
            print(curr_list[1])
        else:
            continue


def get_ticker_day_info(ticker_list, date):

    ticker_day_info = {}
    for ele in ticker_list:
        time.sleep(0.2)  # after 0.2s give a request
        ticker = ele

        date = date
        year = int(int(date)/10000)
        season = math.ceil(int(date[0:6]) % 100/3)
        rlt_list = get_one_ticker_day_info(
            'https://quotes.money.163.com/trade/lsjysj_' + ticker + '.html?year=' + str(year) + '&season=' + str(season), date)
        ticker_day_info[ticker] = rlt_list
    return ticker_day_info


def get_ticker_day_info_from_eastmoney(url, date):
    result_byte = requests.get(url).content
    result_str = str(result_byte, 'utf-8')

    result_json = re.findall(r'{.*}', result_str)

    result_json = result_json[0]
    print(len(result_json))

    print(result_json)
    print()


if __name__ == '__main__':

    ticker = '000001'
    get_ticker_day_info_from_eastmoney('https://85.push2his.eastmoney.com/api/qt/stock/kline/get?cb=jQuery35105512506074409462_1672128865146&secid=0.' + ticker +
                                       '&ut=fa5fd1943c7b386f172d6893dbfba10b&fields1=f1,f2,f3,f4,f5,f6&fields2=f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61&klt=101&fqt=1&end=20500101&lmt=1000000&_=1672128865171', "20221212")

    ticker_list = ['000721', '601318', '600893', '001338']
    date = '20221116'
    rlt = get_ticker_day_info(ticker_list, date)
    print(rlt)


# https: // blog.csdn.net/qq_19006223/article/details/109134517
